package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.jwt.utils.AppJwtUtil;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.LoginDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.AccountService;
import com.usian.utils.common.AesUtil;
import com.usian.utils.common.BCrypt;
import com.usian.utils.common.MD5Utils;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AccountServiceImpl extends BaseServiceImpl<ApUserMapper, ApUser> implements AccountService {
    @Value("${aes-key}")
    private String aesKey;
    @Override
    @SneakyThrows
    public ResponseResult login(LoginDto dto) {
        if (dto == null || StringUtils.isBlank(dto.getPhone()) || StringUtils.isBlank(dto.getPassword()))
            return paramError;
        ApUser user = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
        if (user == null) return ResponseResult.errorResult(5003, "用户不存在");
        String md5Result = AesUtil.decryptAES(dto.getPassword(), aesKey);
        boolean checkResult = BCrypt.checkpw(md5Result, user.getPassword());
        if (checkResult){
            Map<String,Object> resultMap = new HashMap<>();
            user.setPassword("");
            resultMap.put("user",user);
            String token = AppJwtUtil.getToken(user.getId().longValue());
            resultMap.put("token",token);
            return success(resultMap);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
    }

    public static void main(String[] args) throws Exception {
        String pwd = "123456";
        String md5 = MD5Utils.encode(pwd);
        System.out.println("md5:" + md5);
        String key = "NIfb&95GUY86Gfgh";
        String aes = AesUtil.encryptAES(md5, key);
        System.out.println("aes:" + aes);
        String aes2md5 = AesUtil.decryptAES(aes, key);
        System.out.println("aes2md5:" + aes2md5);
        String salt = BCrypt.gensalt();
        System.out.println("salt:" + salt);
        String bcrypt = BCrypt.hashpw(aes2md5, salt);
        System.out.println("bcrypt:" + bcrypt);
        boolean checkpw = BCrypt.checkpw(aes2md5, bcrypt);
        System.out.println(checkpw);
    }
}
